<template>
  <div class="pannel-account">
    <el-form
      :model="account"
      :rules="accountRules"
      :label-width="150"
      size="large"
      status-icon
      ref="formRef"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model.trim="account.userName"
          placeholder="请输入用户名"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model.trim="account.phonenumber" maxlength="11" />
      </el-form-item>
      <el-form-item label="邮 箱" prop="email">
        <el-input v-model.trim="account.email" />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model.trim="account.realName"
          placeholder="请输入真实姓名"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="身份证号码" prop="number">
        <el-input
          v-model.trim="account.number"
          placeholder="请输入身份证号码"
          maxlength="18"
        />
      </el-form-item>
      <el-form-item label="身份证图片" prop="certificatePath">
        <el-upload
          v-model:file-list="fileList"
          action=""
          :limit="2"
          :class="{ hide: hideUploadBtn }"
          list-type="picture-card"
          accept=".jpg,.jpeg,.png"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-upload="handleUpload"
        >
          <el-icon><Plus /></el-icon>
          <template #tip> 图片大小不能超过5M </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="短信验证码" prop="smsCode">
        <el-input v-model.trim="account.smsCode" maxlength="6">
          <template #append>
            <el-button @click="getSmsCode">{{ sendText }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model.trim="account.password" show-password maxlength="20" />
      </el-form-item>
      <el-form-item label="确认密码" prop="surePassWord">
        <el-input v-model.trim="account.surePassWord" show-password maxlength="20" />
      </el-form-item> </el-form
    >、
    <Img-preview v-model:show="imgShow" :imgs="[imgUrl]" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormRules } from "element-plus";
import { ElForm, ElMessage } from "element-plus";
import { sendMsg, upload } from "@/api/cloud/index";
import { register } from "@/api/registerApi";
import router from "@/router";

const props = defineProps({
  // 提交中
  loading: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["update:loading"]);

const baseURL = import.meta.env.VITE_BASE_URL;
const fileList = ref<any>([]); //上传身份证
const hideUploadBtn = ref(false); //隐藏上传按钮开关
const fileNameList = ref<any>([]); //身份证fileName数组
const imgUrl = ref("");
const imgShow = ref(false);
const sendText = ref("获取验证码");
// 表单数据
const account = reactive<Register>({
  userName: "",
  userType: "01",
  password: "",
  realName: "",
  number: "",
  phonenumber: "",
  surePassWord: "",
  email: "",
  smsCode: "",
  certificatePath: "",
});

interface Register {
  userName?: string;
  userType?: string;
  password?: string;
  surePassWord?: string;
  phonenumber?: string;
  email?: string;
  smsCode?: string;
  realName?: string;
  number?: string;
  certificatePath?: string;
}

const formRef = ref<InstanceType<typeof ElForm>>();
// 校验规则
const accountRules: FormRules = {
  userName: [
    { required: true, message: "必须输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度必须在2到20个字符之间", trigger: "blur" },
  ],
  realName: [
    { required: true, message: "必须输入真实姓名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度必须在2到20个字符之间", trigger: "blur" },
  ],
  number: [{ required: true, message: "必须输入身份证号码", trigger: "blur" }],
  certificatePath: [{ required: true, message: "必须上传身份证照片", trigger: "blur" }],
  phonenumber: [
    { required: true, message: "必须输入手机话", trigger: "blur" },
    {
      pattern: /^1\d{10}$/,
      message: "必须是正确的手机号格式",
      trigger: "change",
    },
  ],
  // smsCode: [{ required: true, message: "必须输入短信验证码", trigger: "blur" }],
  email: [
    { required: true, message: "必须输入邮箱", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/,
      message: "必须是正确的邮箱格式",
      trigger: "change",
    },
  ],
  password: [
    { required: true, message: "必须输入密码", trigger: "blur" },
    {
      pattern: /^[\w!@#$%^&*()_+=\-.,\/?:;'"<>~`]{5,20}$/,
      message: "必须是5~20的数字、字母或字符组成",
      trigger: "change",
    },
  ],
  surePassWord: [
    { required: true, message: "必须输入确认密码", trigger: "blur" },
    {
      pattern: /^[\w!@#$%^&*()_+=\-.,\/?:;'"<>~`]{5,20}$/,
      message: "必须是5~20的数字、字母或字符组成",
      trigger: "change",
    },
    {
      validator: (rule, value) => {
        if (value != account.password) {
          return Promise.reject("两次密码不一致");
        }
        return Promise.resolve();
      },
      trigger: "blur",
    },
  ],
};

// 移除身份证
const handleRemove = (file: any) => {
  fileList.value = fileList.value.filter((item: any) => item != file.name);
  fileNameList.value = fileNameList.value.filter((item: any) => item != file.name);
  account.certificatePath = fileNameList.value.join(",");
  if (fileList.value.length < 2) {
    hideUploadBtn.value = false;
  } else {
    hideUploadBtn.value = true;
  }
};

// 预览身份证
const handlePreview = (file: any) => {
  imgUrl.value = file.url;
  imgShow.value = true;
};

// 可以获取图片参数
const handleUpload = (file: any) => {
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过5M");
    return;
  }
  const formData = new FormData();
  formData.append("file", file);
  upload(formData).then((res: any) => {
    fileNameList.value.push(res.fileName);
    account.certificatePath = fileNameList.value.join(",");
    fileList.value.push({ name: res.fileName, url: baseURL + res.fileName });
    if (fileList.value.length < 2) {
      hideUploadBtn.value = false;
    } else {
      hideUploadBtn.value = true;
    }
  });
};

//获取验证码
const getSmsCode = () => {
  if (account.phonenumber == "") {
    ElMessage.error("请输入手机号！");
    return;
  }
  if (sendText.value != "获取验证码") {
    return;
  }
  sendMsg({ phone: account.phonenumber }).then((res: any) => {
    if (200 == res.code) {
      ElMessage.success("短信发送成功！");
      let count = 60;
      let timer = setInterval(() => {
        sendText.value = count + "秒后重新获取";
        count--;
        if (count == 0) {
          sendText.value = "获取验证码";
          clearInterval(timer);
        }
      }, 1000);
    }
  });
};

// 注册
const loginAction = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      let data = Object.assign({}, account) as any;
      delete data.surePassWord;
      data.nickName = data.userName;
      if (account.password == account.surePassWord) {
        emits("update:loading", true);
        register(data)
          .then((res: any) => {
            ElMessage.success("注册成功，请登录");
            router.push("login");
          })
          .finally(() => {
            emits("update:loading", false);
          });
      } else {
        ElMessage.error("两次密码不一致");
      }
    }
  });
};

defineExpose({
  loginAction,
});
</script>

<style lang="less" scoped>
.hide {
  /deep/.el-upload--picture-card {
    display: none !important;
  }
}
/deep/ .el-upload-list__item {
  transition: none !important;
}
.test-account {
  font-size: 12px;
  color: #000;
}
.verify-code {
  display: flex;
  width: 100%;
  .get-btn {
    margin-left: 8px;
  }
}
</style>
